#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

#include <windows.h>

#include <utils.h>

int read_entire_file(const char  *fn,
                     char       **result)
{
    HANDLE h = CreateFile(fn, GENERIC_READ, 0, NULL, OPEN_EXISTING,
                          FILE_ATTRIBUTE_NORMAL, NULL);
    if (h == INVALID_HANDLE_VALUE) {
        message(MSG_LEVEL_ERROR, "open file `%s': %d\n",
                fn, GetLastError());
        return -1;
    }

    int size = GetFileSize(h, NULL);
    if (size <= 0) {
        CloseHandle(h);
        return -1;
    }

    char *buf = (char *) malloc (size + 1);

    if (buf == NULL) {
        message(MSG_LEVEL_ERROR, "alloc memory %d bytes failed: %s\n",
                size, strerror(errno));
        CloseHandle(h);
        return -1;
    }

    DWORD nbytes_read = 0;
    if (!ReadFile(h, buf, size, &nbytes_read, NULL)) {
        message(MSG_LEVEL_ERROR, "read file `%s' failed, %d\n",
                fn, GetLastError());
        CloseHandle(h);
        free(buf);
        return -1;
    }

    CloseHandle(h);

    if (size != nbytes_read) {
        free(buf);
        return -1;
    }

    buf[size] = 0;
    *result = buf;
    return size;
}
